package com.itheima.web.filter;

import com.itheima.domain.User;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * @author ：sean
 * @date ：Created in 2022/4/28
 * @description ：
 * @version: 1.0
 */
@WebFilter("/api/*")
@Slf4j
public class LoginCheckFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) rep;
		String uri = request.getRequestURI();
		log.info("【登录过滤器/*,uri:{}】",uri);
		if(uri.endsWith("/api/user")){
			log.info("【登录接口,{} 放行】",uri);
			chain.doFilter(request,response);
			return;
		}
		HttpSession httpSession = request.getSession();
		Object user = httpSession.getAttribute("user");
		if(user == null){
			log.info("【未登录-返回登录页面,{}】",uri);
			response.sendRedirect("/webcase/login.html");
			return;
		}
		chain.doFilter(request,response);
		log.info("【已登录,{} 放行】",uri);
	}

	@Override
	public void destroy() {

	}
}
